{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "URL: http://bokeh.pydata.org/en/latest/docs/gallery/les_mis.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import holoviews as hv\n",
    "hv.extension('bokeh')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Declare data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bokeh.sampledata.les_mis import data\n",
    "\n",
    "nodes = data['nodes']\n",
    "names = [node['name'] for node in sorted(data['nodes'], key=lambda x: x['group'])]\n",
    "\n",
    "N = len(nodes)\n",
    "counts = np.zeros((N, N))\n",
    "for link in data['links']:\n",
    "    counts[link['source'], link['target']] = link['value']\n",
    "    counts[link['target'], link['source']] = link['value']\n",
    "    \n",
    "xname = []\n",
    "yname = []\n",
    "color = []\n",
    "alpha = []\n",
    "for i, node1 in enumerate(nodes):\n",
    "    for j, node2 in enumerate(nodes):\n",
    "        xname.append(node1['name'])\n",
    "        yname.append(node2['name'])\n",
    "\n",
    "        alpha.append(counts[i,j])\n",
    "\n",
    "        if node1['group'] == node2['group']:\n",
    "            color.append(node1['group'])\n",
    "        else:\n",
    "            color.append('lightgrey')\n",
    "\n",
    "ds = hv.Dataset((xname, yname, color, alpha), kdims=['x', 'y', 'Cluster', 'Occurences'])\n",
    "overlaid = ds.to(hv.HeatMap, ['x', 'y'], ['Occurences']).overlay()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_opts = dict(height=800, width=800, xaxis='top', logz=True, xrotation=90,\n",
    "                 fontsize={'ticks': '7pt', 'title': '18pt'}, invert_xaxis=True, tools=['hover'],\n",
    "                 labelled=[], clipping_colors={'NaN':(1,1,1,0.)})\n",
    "\n",
    "cmaps = ['Greys', 'Reds', 'Greys', 'Greens', 'Blues',\n",
    "         'Purples', 'Oranges', 'Greys', 'Greys', 'PuRd', 'Reds', 'Greys']\n",
    "combined = hv.Overlay([o(style=dict(cmap=cm), plot=plot_opts).sort()\n",
    "                       for o, cm in zip(overlaid, cmaps)], label='LesMis Occurences')\n",
    "combined"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hv.Layout([c(plot=dict(width=300, height=300))\n",
    "           for c in combined if len(c)>10][:-1],\n",
    "          label='LesMis Large Clusters').cols(3)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
